<template>
  <div class="flex-row autoGrow replyContainer">
    <choose-service-account
      :multiple="false"
      @serviceChange="serviceChange"
    >
      <div class="autoGrow welcomeOptions flex-column">
        <div class="toggleOwner">
          <label>
            <input type="radio"
            name="manager"
            value="manager"
            @change="changeGroupType"
            :checked="groupType=='manager'"> 群主
          </label>
          <label>
            <input type="radio"
            name="manager"
            value="member"
            @change="changeGroupType"
            :checked="groupType=='member'"> 非群主
          </label>
          
        </div>
        <search placeholder="请输入关键词" @change="changeSearch"></search>
        <div class="groupListTitle">
          <label><input type="checkbox" v-model="selectAll"> 群（{{checkedGroups.length}}/{{groups ? groups.length : 0}})</label>
        </div>
        <div class="groupList autoGrow">
           <label v-for="(group) in filterGroups" :key="group.id">
            <user-list-item
              :showBadge="false"
              :showLastMessage="false"
              currentUserWxid=""
              :item="group">
              <template v-slot:checkbox>
                <input type="checkbox"
                  :checked="checkedGroups.includes(group.wxid)"
                  :disabled="hasSetingGroups.includes(group.id) && !editSetingGroups.includes(group.id)"
                  class="select"
                  @change="toggleSelect(group)">
              </template>
              <template v-slot:bottomInfo>
                <div>
                  <span>群成员{{group.personnum}} </span>
                  <span>非好友{{group.personnum - group.friendNum}}</span>
                </div>
              </template>
              <template v-slot:attachInfo>
                <div class="fontGrey">
                  {{hasSetingGroups.includes(group.id) ? '已设置' : ''}}
                </div>
              </template>
            </user-list-item>
          </label>
        </div>
      </div>
    </choose-service-account>
    <div class="settingOption flex-column">
      <div class="subTitle">关键词设置</div>
      <div class="option flex-row">
        <inputTags :maxlength="10" title="关键字" :tags="keywords" @change="addKeywords" />
      </div>
      
      <div class="option flex-row welcomeName">
        <span>是否@进群成员</span>
        <el-radio-group v-model="replytype" class="option-at-friend">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>  
      </div>
      <messageButtonGroup
            :csid="csid"
            :wxid="service&&service.wxid"
            @create="settingReply"
          />
        <el-divider v-if="replys.length"></el-divider>
        <div class="quick-plane">
          <div class="quick-item" v-for="(reply, index) in replys" :key="index">
            <div class="quick-item-createtime" style="text-align:right">
                <i @click.stop="replys.splice(index,1)" class="el-icon-close quick-item-close"></i>
            </div>
            <messageCard :message="reply" />
          </div>
        </div>
      <div class="submit flex-row">
        <button class="layui-btn layui-btn-sm" @click="submitSetting">提 交</button>
      </div>
    </div>
    <!-- 关键词回复记录 -->
    <div class="detail-container autoGrow flex-column">
        <fieldset><legend><span name="fieldset">关键词回复记录</span></legend></fieldset>
        <template v-if="welcomeList.length">
            <el-collapse accordion v-model="accordion">
                <el-collapse-item class="detail-item" v-for="(record,index) in welcomeList" :key="record.id" :name="index+''">
                    <div slot="title" class="flex-row detail-content">
                        <img class="detail-avatar" :src="service.avatar" />
                        <div class="flex-column detail-info">
                            <span class="detail-keyword">关键词：<span style="color:#FF5722">{{record.keyword}}</span></span>
                            <span class="fontGrey">{{formatTime(record.createTime)}} <span class="fontGrey">配置了 {{record.itemcount}} 个群</span></span>
                        </div>
                        <div>
                            <button type="button" class="layui-btn layui-btn-sm">详情</button>
                            <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" @click.stop="deleteRecord(record,index)">删除</button>
                        </div>
                    </div>
                    <div class="layui-tab layui-tab-card detail-setting">
                        <ul class="layui-tab-title">
                            <li class="layui-this">回复记录</li>
                            <li>回复内容</li>
                        </ul>
                        <div class="layui-tab-content">
                            <div class="layui-tab-item layui-show">
                                <div class="detail-setting-list" v-if="record.wxReplyRecord.length && record.wxReplyRecord[0].groups && record.wxReplyRecord[0].groups[0] &&record.wxReplyRecord.filter(item=>item.replycount)[0]">

                                    <label class="flex-row account-item detail-setting-item" v-for="item in record.wxReplyRecord.filter(item=>item.replycount)" :key="item.id">
                                        <group
                                            v-if="item.groups[0]"
                                            :name="item.groups[0].groupname"
                                            :avatar="item.groups[0].avatar"
                                            :member="item.groups[0].personnum"
                                            :friend="item.groups[0].friendNum"
                                        />
                                        <span class="fontGrey account-item-time" v-if="item.updatetime">
                                            {{ formatTime(item.updatetime) }}
                                        </span>
                                        <span class="fontGrey account-item-time" v-if="item.updatetime">
                                            已发送 {{ item.replycount }} 次
                                        </span>
                                        <button @click="toChat(item)" type="button" class="layui-btn layui-btn-sm">查看</button>
                                    </label> 
                                    
                                </div>
                                <div class="data-empty" v-else>
                                    <span class="fontGrey">暂无数据</span>
                                </div>
                                
                            </div>
                            <div class="layui-tab-item">
                                <div class="detail-setting-list">
                                    <div class="detail-record-content">
                                        <messageButtonGroup 
                                            :csid="csid"
                                            :wxid="accountChecked.wxid"
                                            @create="editMessage"
                                        /> 
                                        
                                        <div class="quick-plane">
                                            <div class="quick-item" v-for="(reply, index) in editRecord.id === record.id?editRecord.messages:record.messages" :key="index">
                                            <div class="quick-item-createtime" style="text-align:right">
                                                <i @click.stop="editRecord.messages.splice(index,1)" class="el-icon-close quick-item-close"></i>
                                            </div>
                                            <messageCard :message="reply" />
                                            </div>
                                        </div> 
                                    </div>
                                    <div class="detail-setting-ctrl">
                                        <div>
                                          是否@
                                          <el-radio-group size="mini" v-model="editRecord.replytype">
                                            <el-radio-button label="1">是</el-radio-button>
                                            <el-radio-button label="0">否</el-radio-button>
                                          </el-radio-group>
                                        </div>
                                        <button type="button" @click="submitEdit(editRecord)" class="layui-btn layui-btn-sm layui-btn-normal" >提交</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-collapse-item>
            </el-collapse>
            
        </template>
        <template v-else>
            <div class="data-empty">
                <span class="fontGrey">暂无数据</span>
            </div>                        
        </template>
    </div>
    <!-- 关键词回复记录 end -->
  </div>
</template>
<script>
import ChooseServiceAccount from '@/components/chooseServiceAccount'
import UserListItem from '@/components/userListItem'
import inputTags from '@/components/input-tags'
import group from '@/components/group'
import Search from '@/components/search'
import pinyin from '@/lib/pinyin'
import Message from '@/components/message'
import messageButtonGroup from '@/components/message-button-group'
import messageCard from '@/components/message-card'
import { mapState, mapMutations, mapActions } from 'vuex'
import { getChatid,getAccountid } from '@/lib/data-translate'

export default {
  name: 'reply',
  data() {
    return {
      replytype:1,

      currentRecord: null,
      service: null,
      selectAll: false,
      groups: [],
      keyword: '',
      groupType: 'manager', // member
      welcomeName: '',
      minCount: '',
      reply: '',
      replys:[],
      welcomeList: [],
      keywords: [],

      checkedGroups: [], // 等待选择的群组
      hasSetingGroups:[], // 已经设置的群组
      editSetingGroups:[], // 已经设置但可编辑群组

      accountChecked:{},
      editRecord:{},
      accordion:''

    }
  },
  components: {
    ChooseServiceAccount,
    UserListItem,
    Search,
    Message,
    messageButtonGroup,
    messageCard,
    group,
    inputTags
  },
  methods: {
    ...mapMutations(['updateUIState']),
    ...mapActions(['addChatByFriend','requestChatMap']),
    serviceChange(services) {
      this.service = services[0]
      this.accordion = ''
      this.init()
    },
    init() {
      this.$api.group.list({
        csid: this.service.csid,
        wxaccount: this.service.wxid
      }).then(data=>{
        this.groups = this.transGroupData(data);
      }).catch(e=>this.$msg(e))
      this.$api.keyword.list({
        csId: this.service.csid,
        wxAccount: this.service.wxid
      }).then(data=>{

        this.welcomeList = data.map(this.getMessages)

      }).catch(e=>this.$msg(e))
    },
    getMessages(item){
      const _msgcontent = JSON.parse(item.msgcontent)
      let messages = []
      if(_msgcontent instanceof Array){
        item.messages = _msgcontent
      }else{
        item.messages = [_msgcontent]
      }
      return item
    },
    changeGroupType(e) {
      this.groupType = e.target.value
    },
    toggleSelect(group) {
      if (this.checkedGroups.includes(group.wxid)) {
        this.checkedGroups = this.checkedGroups.filter(item=>{
          return item!=group.wxid
        })
      } else {
        this.checkedGroups.push(group.wxid)
      }
    },
    changeSearch(val) {
      this.keyword = val
    },
    settingReply(reply) {
      this.replys.unshift(reply)
    },
    deleteRecord(record, i) {
      this.$api.keyword.deleteSetting({
        id: record.id
      }).then(()=>{
        this.welcomeList.splice(i, 1)
      }).catch(e=>this.$msg(e))
    },
    chooseMessageRecord(index){
      this.editRecord = index ===''?{}:this.welcomeList[+index]
      this.editRecord.replytype = this.editRecord.replytype||0
      console.log(this.editRecord)
    },
    editMessage(message){
      console.log('editMessage')
      this.editRecord.messages.push(message)  
    },
    toggleDetail(index) {
      const record = this.welcomeList[index];
      this.$set(this.welcomeList, index, {
        ...record,
        showDetail: !record.showDetail
      })
    },
    recordtabclick(index,val){
      const record = this.welcomeList[index];
      this.$set(this.welcomeList, index, {
        ...record,
        tab: val
      })
    },
    changeKeyword(index, e) {
      this.$set(this.keywords, index, e.target.value)
    },
    addKeywords(keywords) {
      if (this.keywords.length == 10) {
        return this.$msg('最多添加10个关键字')
      }
      this.keywords = keywords
    },
    submitSetting() {
      const replys = [...this.replys]
      if (!this.service) return this.$msg("请选择客服账号")
      if (!this.keywords.length) return this.$msg("请输入关键词")
      if (!this.checkedGroups.length) return this.$msg("请选择设置的群")
      if (!replys.length) return this.$msg("请选择回复的内容")
      const groups = this.groups.filter(item=> this.checkedGroups.includes(item.id))

      this.$api.keyword.insert({
        groupNoList: groups.map(g=>g.groupno),
        csid: this.service.csid,
        wxaccount: this.service.wxid,
        keyword: this.keywords.filter(word=>word.trim()!='').join(','),
        msgcontent: JSON.stringify(replys.reverse()),
        replytype: this.replytype,
        type:0
     }).then(rs=>{
       this.$msg('添加成功')
       this.welcomeList.unshift(this.getMessages(rs))
        this.keywords = []
        this.replys = []


     }).catch(e=>this.$msg(e))
    },
    submitEdit(editRecord){
      if(editRecord.id){
        const { id,csid,wxaccount,keyword,type ,messages,replytype } = editRecord;
        if(!messages.length) return this.$msg("请选择回复的内容")
        const msgcontent = JSON.stringify(messages);
        this.$api.keyword.updateSetting({
            id,csid,wxaccount,keyword,type ,msgcontent ,replytype:replytype||0  
        }).then(rs=>{
            this.$msg('修改成功')
            this.welcomeList.forEach(element => {
                if(element.id === id){
                    element.messages = messages     
                }    
            });
            this.$forceUpdate()
        }).catch(e=>this.$msg)
      }
    },
    toChat(record){
      const { wxaccountid,groupaccount,csid,groups } = record;
      
      const accountid = getAccountid(this.accountMap,csid,wxaccountid)
      const chatid = getChatid(csid,accountid,groupaccount)
      const group = groups[0]

      this.updateUIState({ accountid })
      this.requestChatMap({csid,wxaccount:wxaccountid})
      .then(rs=>{
        if(rs&&rs[0]){
          let _group = {
            csid:group.csid,
            wxaccount:group.wxaccount,
            friendnick:group.groupname,
            friendNick:group.groupname,
            friendwxid:group.groupno,
            avatar:group.avatar
          }
          
          this.addChatByFriend(_group) // 添加到chat相关
          this.$router.push({
              name: 'home',
          })
          console.log('chatid',chatid)
          setTimeout(()=>{
              this.updateUIState({ chatid })
          },0)
            
        }
            
      })
      // this.addChatByFriend({...friend,id:undefined}) // 添加到chat相关
    }
  },
  computed: {
    ...mapState(['uistate','accountMap']),
    csid(){
      return this.uistate.adminid
    },
    filterGroups(){
      const isShowManager = this.groupType === 'manager'
      const keyword = pinyin.getFullChars(this.keyword).toLocaleLowerCase() 

      return this.groups.filter(item=>{
        const chars = pinyin.getFullChars(item.groupname).toLocaleLowerCase() ;
        if(isShowManager){
          return item.isfirst === 1 && chars.indexOf(keyword)>-1
        }else{
          return item.isfirst !== 1 && chars.indexOf(keyword)>-1
        }
         
      })
      
    },
  },
  watch: {
    accordion(val,old){
        this.chooseMessageRecord(val)
    },
    selectAll(val) {
      if (val) {
        this.checkedGroups = this.groups.map(g=>g.wxid)
      } else {
        this.checkedGroups = []
      }
    },
  }
}
</script>
<style scoped>
/* 记录  */
.detail-container{
    background-color: #f2f2f2;
    padding:15px;
    box-sizing: border-box;
    height: 100%;
    overflow: auto;
}
.detail-container fieldset {
    border: none;
    padding: 0;
    border-top: 1px solid #ddd;
    margin-bottom: 10px;
} 
.detail-record-content{
    position: relative;
    padding: 0 20px;
    min-height: 50px;
}
.detail-container fieldset legend {
    margin-left: 20px;
    padding: 0 10px;
    font-size: 22px;
    font-weight: 300;
} 
.detail-item{
    padding: 10px 16px;
    background-color: #fff;
    border-radius: 4px;
    border-left: 5px solid #50bfff;
    margin: 5px 0;  
    cursor: pointer; 
}
.detail-item >>> .el-collapse-item__header,
.detail-item >>> .el-collapse-item__wrap{
    border-bottom: 0
}
.detail-item >>> .el-collapse-item__content{
    padding-bottom: 0
}
.detail-avatar{
    width: 40px;
    height: 40px;
    background-color: #ccc;
    box-sizing: border-box;
    border-radius: 3px;
}
.detail-info{
    flex:1;
    padding-left: 10px;
    height: 40px;
    justify-content: center;
    line-height: 20px;
}
.detail-keyword{
    font-size: 16px;
}
.detail-setting{
    margin-top: 10px;
}
.detail-setting .layui-tab-item{
    height: 180px;
}
.data-empty{
    display: flex;
    justify-content: center;
    align-items: center;
    flex: 1;
    height: 100%;
}
.detail-setting .layui-tab-content{
    padding: 0
}
.detail-content{
    align-items: center;
    justify-content: space-between;
    flex:1;
    padding-right: 20px;
}
.detail-setting-list{
    flex: 1;
    height: 100%;
    overflow: auto;
    padding:10px 0;
    box-sizing: border-box;
}
.detail-setting-item{
    margin-bottom: 0
}
.detail-setting-ctrl{
    margin:10px 20px;
    text-align: right;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;

}
/* 记录 end  */
.listContainer .recordItem .targetsList{
  padding:10px;
}
.quick-plane{
    /* padding: 0 10px;
    background: #f1f1f1; */
}
.quick-item{
    padding: 10px 16px;
    background-color: #fff;
    border-radius: 4px;
    border-left: 5px solid #50bfff;
    margin: 5px 0;  
    cursor: pointer; 
    box-shadow: 0px 1px 1px 1px #ddd;
    transition:transform 200ms;
    padding-right: 10px;
}

.account-list{
    height:100%;
    overflow: auto
}
.account-item{
    align-items: center;
    padding: 10px;
    cursor: pointer;
}
.account-item.selected{
    background-color: #eee
}
.account-item:last-child{
    margin-bottom: 0
}
.account-item-time{
    flex:1
}


/* @群成员 */
.option-at-friend{

}
</style>
